using System;

namespace PTP.Core
{
  public delegate void DebugWriter(string category, string message);

  public static class DebugUtil
  {
    //some common categories so you know what to filter out

    public const string ReadBytesCategory = "RBYTE";
    public const string WriteBytesCategory = "WBYTE";
    
    public static event DebugWriter WriteMessage;

    public static bool TraceEnabled
    {
      get
      {
        return WriteMessage != null;
      }
    }

    public static void Write(string category, string message)
    {
      if (WriteMessage != null)
        WriteMessage(category, message);
    }


    private const string hexNumbers = "0123456789ABCDEF";
    static int numberCharArrayLength = 64;
    static char[] numberCharArray = null;

    private static void clearNumberCharArray()
    {
      if (numberCharArray == null)
        numberCharArray = new char[numberCharArrayLength];
      for (int i = 0; i < numberCharArrayLength; i++)
        numberCharArray[i] = (char)0;
    }


    public static string ToHexDigits(uint val)
    {
      clearNumberCharArray();

      int startIndex = numberCharArrayLength;
      do
      {
        numberCharArray[--startIndex] = hexNumbers[(int)(val & 0xF)];
        val = val >> 4;
      }
      while (val != 0);
      return new string(numberCharArray, startIndex, numberCharArrayLength - startIndex);
    }

    public static string ToHexDigits(byte[] buffer, int offset, int count)
    {
      const int width = 3;
      int requiredSpace = (count * width - 1);
      if (requiredSpace > numberCharArrayLength)
      {
        numberCharArrayLength = requiredSpace;
        numberCharArray = null;
      }

      clearNumberCharArray();

      for (int i = 0; i < count; i++)
      {
        int charIndex = i * width;
        int index = i + offset;
        numberCharArray[charIndex] = hexNumbers[(int)((buffer[index]>>4) & 0xF)];
        numberCharArray[charIndex + 1] = hexNumbers[(int)(buffer[index] & 0xF)];
        if (charIndex + 2 < numberCharArrayLength)
          numberCharArray[charIndex + 2] = ' ';
      }

      return new string(numberCharArray, 0, requiredSpace);
    }
  }
}
